import React, { useState, useEffect } from 'react';
import { Card, Form, Row, Col, Input, Select, Button, Table, Popconfirm, message, Badge, Divider, DatePicker } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import PaymentDetail from './PaymentDetail';
import { withRouter } from 'react-router-dom';
import { formatBalance } from '@/utils/utils';
import { useDebounceFn  } from '@/utils';
import moment from 'moment';
import {
  rechargeSum,
  rechargePage,
} from '@/api/order'
import '../index.scss';

const Order = (props) => {
  const [searchForm] = Form.useForm();
  const { RangePicker } = DatePicker;
  // 筛选数据
  const [values] = useState({
    "time": [moment(),moment()],
    "mainOrderId": "",
    "userName": "",
    "nickName": "",
    "status": "",
    "orderNo": "",
    "riskRemark": "",
    "userType": "",
  })
  // 存款订单状态
  const orderStatus = [
    // { value: '-1', label: '全部' },
    { value: '0', label: '未支付' },
    { value: '1', label: '已支付' },
    { value: '2', label: '已受理' },
    { value: '3', label: '已审核' },
    { value: '4', label: '成功' },
    { value: '5', label: '失败' },
    
    { value: '10001', label: '出售中' },
    { value: '10002', label: '暂停出售' },
    { value: '10004', label: '交易中' },
    { value: '10007', label: '交易成功' },
    { value: '10009', label: '超时卖家取消交易' },
    { value: '10003', label: '待交易' },
    { value: '10005', label: '取消交易' },
    { value: '10006', label: '已支付' },
    { value: '10008', label: '已评价' },
    { value: '10010', label: '超时买家取消交易' },
    { value: '10011', label: '超时自动完成交易' },
    { value: '10012', label: '工单发货' },
    { value: '10013', label: '交易失败' },
  ]

  const userTypeList = [
    { value: '', label: '全部' },
    { value: '1', label: '真实会员' },
    { value: '2', label: '内部会员' },
  ]
  
  const { history } = props
  // 显示详情
  const [showDetail, setShowDetail] = useState(false)
  const [detailParams, setDetailParams] = useState(null)
  // 分页
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [dataSource, setDataSource] = useState([])
  const [pageSum, setPageSum] = useState(0)
  const [allSum, setAllSum] = useState(0)
  
  
  // 面包屑
  const breadcrumbList = ['订单管理', '买入单']
  // 布局
  const layout1 = { sm: 24, md: 12, lg: 12, xl: 6, xxl: 6 };
  const labelCol = { sm: 24, md: 8, lg: 8, xl: 8 };
  const wrapperCol = { sm: 24, md: 16, lg: 16, xl: 16 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 24, xxl: 24 };
  
  const [formData, setFormData] = useState(values)
  let [loading, setLoading] = useState(false)
  // 表单头部
  const columns = [
    {
      title: '主订单号',
      dataIndex: 'mainOrderNo',
      key: 'mainOrderNo',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '订单编号',
      dataIndex: 'merchantOrderId',
      key: 'merchantOrderId',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '会员账号',
      dataIndex: 'merchantName',
      key: 'merchantName',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '会员昵称',
      dataIndex: 'merchantNickName',
      key: 'merchantNickName',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '风控备注',
      dataIndex: 'riskRemark',
      key: 'riskRemark',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '买入数量',
      dataIndex: 'amount',
      key: 'amount',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '买入单价',
      dataIndex: 'price',
      key: 'price',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '申请时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '完成时间',
      dataIndex: 'payTime',
      key: 'payTime',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text, record) => orderStatus.filter(item => parseInt(item.value) === parseInt(text))[0].label,
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          <a
            onClick={() => {
              goDetail({
                edit: false,
                id: record.merchantOrderId
              })
            }}
          >
            查看
          </a>
        </>;
      },
    }
    
    
    
    
  ];
  
  // 提交弹框表单做防抖处理
  const handleSubmit = useDebounceFn((values) => {
    onFinish(values)
    getAll(values)
  }, 1500, true);
  const onFinish = async (values) => {
    let formData = {}
    for (let key in values) {
      if (values[key]) {
        formData[key] = values[key]
      }
    }
    try {
      setPageSum(0)
      setLoading(true)
      let params = {
        ...formData,
        startDate: formData&&formData.time ? moment(formData.time[0]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        endDate: formData&&formData.time ? moment(formData.time[1]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        pageSize,
        currentPage,
      }
      delete params.time
      let res = await rechargePage(params)
      if(res.code === 0){
        
        if(res.data.records && res.data.records.length>0){
          let all = 0;
          res.data.records.forEach(item=>{
            all += item.receivedAmount;
          })
          setPageSum(all)
        }
        setDataSource(res.data.records || [])
        setTotal(res.data.total)
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  };
  
  const getAll = async (values) => {
    let formData = {}
    for (let key in values) {
      if (values[key]) {
        formData[key] = values[key]
      }
    }
    try {
      let params = {
        ...formData,
        startDate: formData&&formData.time ? moment(formData.time[0]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        endDate: formData&&formData.time ? moment(formData.time[1]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        pageSize,
        currentPage,
      }
      delete params.time
      let res = await rechargeSum(params)
      if(res.code === 0){
        setAllSum(res.data)
      }
    } catch (error) {
      console.log(error)
    }
  };
  
  const goDetail  = (data) => {
    setDetailParams(data);
    setShowDetail(true);
  }
  
  // 首次更新
  useEffect(() => {
    onFinish()
    getAll()
    return () => { 
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  // 初始化
  return (
  <div>
    {
      showDetail === false
      ?
      <div>
        <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
        <div className='agent-main'>
        <Form
          initialValues={values} 
          form={searchForm} 
          onFinish={(val) => {
            handleSubmit(val)
          }}>
            <Card className="formCard" style={{ width: '100%' }} bordered={false}>
              <Row>
                <Col {...layout1}>
                  <Form.Item
                    name="time"
                    className="formItem"
                    label="申请时间"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <RangePicker allowClear={false} style={{width:'100%'}} />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="mainOrderId"
                    className="formItem"
                    label="主订单号"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="请输入主订单号" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="userName"
                    className="formItem"
                    label="会员账号"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="请输入会员账号" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="nickName"
                    className="formItem"
                    label="会员昵称"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="请输入会员昵称" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="status"
                    className="formItem"
                    label="订单状态"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={orderStatus} />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="orderNo"
                    className="formItem"
                    label="订单号"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="请输入订单号" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="riskRemark"
                    className="formItem"
                    label="风控备注"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="输入风控备注" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="userType"
                    className="formItem"
                    label="会员类型"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={userTypeList} />
                  </Form.Item>
                </Col>
                <Col {...layoutbtn}>
                  <span className="buttonLeft">
                    <Button type="primary" htmlType="submit">
                      查询
                    </Button>
                    <Button
                      className="reset-btn"
                      type="default"
                      onClick={() => {
                        searchForm.resetFields()
                      }}
                    >
                      重置
                    </Button>
                  </span>
                </Col>
              </Row>
            </Card>
          </Form>
          <div className='table-box'>
            <Card>
              <div className='table'>
                <Table
                  loading={loading}
                  size='middle'
                  bordered
                  scroll={{ x: 1224 }}
                  rowKey={'id'}
                  className='antd-table'
                  dataSource={dataSource}
                  pagination={{
                    size: 'default',
                    current: currentPage,
                    total: total,
                    showSizeChanger: true,
                    pageSize: pageSize,
                    onChange: (page, pagesize) => {}
                  }}
                  columns={columns} />
              </div>
              <div className="bottom">
                <span>总金额：{allSum}</span>
                <span>当前页汇总金额：{pageSum}</span>
              </div>
            </Card>
          </div>
        </div>
      </div>
      :
      <PaymentDetail detailParams={detailParams} back={()=>{setShowDetail(false)}} />
    }
  </div>
  )
}
export default withRouter(Order)